import axios from "axios";
import qs from "qs";
import router from "../router";
import Cookie from "js-cookie"
axios.defaults.withCredentials = true;
 axios.defaults.baseURL = "http://192.168.8.128:8080";
// axios.defaults.baseURL = "http://csadmin.pigbanjia.com/";
axios.defaults.timeout = 8000;
axios.defaults.headers = {
    "Content-Type": "application/x-www-form-urlencoded"
};

// request全局拦截
axios.interceptors.request.use(
    config => {
        let regin = Cookie.get("regid")
        if(config.url == "/fronted/shoppingcart/shoppingCartList.shtml" ||
           config.url == "/fronted/orderinfo/orderList.shtml" ||
           config.url == "/fronted/shoppingcart/shoppingCartOperation.shtml" ||
           config.url == "/fronted/shoppingcart/proConfirmInfo.shtml" ||
           config.url == "/fronted/orderinfo/orderCommit.shtml" || 
           config.url == "/fronted/orderinfo/orderBatchNumber.shtml" ||
           config.url == "/fronted/deliveryaddress/addressSetDefault.shtml" ||
           config.url == "/fronted/deliveryaddress/addressOperation.shtml" ||
           config.url == "/fronted/deliveryaddress/addressOperation.shtml"
           ){
            if(!regin){
                router.push({ path: "/login"})   
            }
        }
        if (config.method === "post") {
            if(regin){
               config.data += `&registerId=${regin}`; 
            } 
        } else if (config.method === "get") {
            if(regin){
               config.params["registerId"] = regin; 
            }  
        }
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);

//response全局拦截
axios.interceptors.response.use(
    response => {
        // if (response.data.status == 1001) {
        //     router.push({
        //         path: "/login"
        //     });
        // }
        return response;
    },
    error => {
        return Promise.reject(error.response.data);
    }
);

export default axios;

export const post = (url, params) => {
    return axios({
        method: "post",
        url: url,
        data: qs.stringify(params)
    });
};

export const get = (url, params) => {
    return axios({
        method: "get",
        url: url,
        params: params
    });
};
